package org.hxzon.tapestry5.validator;

import java.math.BigDecimal;

import org.apache.tapestry5.Field;
import org.apache.tapestry5.MarkupWriter;
import org.apache.tapestry5.ValidationException;
import org.apache.tapestry5.ioc.MessageFormatter;
import org.apache.tapestry5.services.FormSupport;
import org.apache.tapestry5.validator.AbstractValidator;
import org.hxzon.util.BigDecimalUtil;

public class Min extends AbstractValidator<BigDecimal, BigDecimal> {
    public Min() {
        super(BigDecimal.class, BigDecimal.class, "min-number");
    }

    public void validate(Field field, BigDecimal constraintValue, MessageFormatter formatter, BigDecimal value) throws ValidationException {
        if (BigDecimalUtil.lessThan(value, constraintValue)) {
            throw new ValidationException(buildMessage(formatter, field, constraintValue));
        }
    }

    private String buildMessage(MessageFormatter formatter, Field field, BigDecimal constraintValue) {
        return formatter.format(constraintValue, field.getLabel());
    }

    public void render(Field field, BigDecimal constraintValue, MessageFormatter formatter, MarkupWriter writer, FormSupport formSupport) {
        formSupport.addValidation(field, "min", buildMessage(formatter, field, constraintValue), constraintValue);
    }
}
